import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
const service = axios.create({
  baseURL: 'http://vue-shop-api-t.itheima.net/api/private/v1',
  timeout: 5000
})

service.interceptors.request.use(config => {
  console.log('所有的请求都要经过这里', config)
  const token = store.state.login.token
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, err => {
  return Promise.reject(err)
})

service.interceptors.response.use(response => {
  console.log('所有的响应都要经过这里', response)
  if (response.data.meta.status === 200) {
    Message.success(response.data.meta.msg)
  }
  if (response.data.meta.status === 400 && response.data.data === null) {
    store.commit('login/delToken')
    router.push('/login')
  }
  return response.data
}, err => {
  return Promise.reject(err)
})

export default service
